package com.beidouin.sensortest;

import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.friendlyarm.AndroidSDK.HardwareControler;

import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;

public class SerialPortActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemSelectedListener,RadioGroup.OnCheckedChangeListener{

    private static final String TAG = "SerialPort";
    private TextView fromTextView = null;
    private EditText toEditor = null;
    private RadioGroup serialport;
    private final int MAXLINES = 200;
    private StringBuilder remoteData = new StringBuilder(256 * MAXLINES);
    //选择串口1 , 或者2
    private String devName ="dev/ttyAMA3";
    private int speed = 115200;
    private int dataBits = 8;
    private int stopBits = 1;
    private int devfd = -1;

    int[] speed_val={1200,4800,9600,19200,38400,47600,115200,230400,460800,500000,576000,921600};
    int[] dataBits_val={5,6,7,8};
    int[] stopBits_val={1,2};

    Spinner speed_spi,dataBits_spi,stopBits_spi;


    Button sendbtn;

    @Override
    public void onDestroy() {
        timer.cancel();
        if (devfd != -1) {
            HardwareControler.close(devfd);
            devfd = -1;
         }
        super.onDestroy();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serial_port);


        String winTitle = devName + "," + speed + "," + dataBits + "," + stopBits;
        setTitle(winTitle);

        sendbtn= (Button) findViewById(R.id.sendButton);
        sendbtn.setOnClickListener(this);
        serialport= (RadioGroup) findViewById(R.id.serialport_choose);
        fromTextView = (TextView)findViewById(R.id.fromTextView);
        toEditor = (EditText)findViewById(R.id.toEditor);

        speed_spi= (Spinner) findViewById(R.id.speed);
        dataBits_spi= (Spinner) findViewById(R.id.dataBits);
        stopBits_spi= (Spinner) findViewById(R.id.stopBits);

        speed_spi.setOnItemSelectedListener(this);
        dataBits_spi.setOnItemSelectedListener(this);
        stopBits_spi.setOnItemSelectedListener(this);
        serialport.setOnCheckedChangeListener(this);

        speed_spi.setSelection(6);
        dataBits_spi.setSelection(3);
        stopBits_spi.setSelection(0);

        /* no focus when begin */
        toEditor.clearFocus();
        toEditor.setFocusable(false);
        toEditor.setFocusableInTouchMode(true);

        //打开串口
        devfd = HardwareControler.openSerialPort( devName, speed, dataBits, stopBits );
        if (devfd >= 0) {
            timer.schedule(task, 0, 500);
        } else {
            devfd = -1;
            fromTextView.append("Fail to open " + devName + "!");
        }
    }

    private final int BUFSIZE = 512;
    private byte[] buf = new byte[BUFSIZE];
    private Timer timer = new Timer();
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (HardwareControler.select(devfd, 0, 0) == 1) {
                        int retSize = HardwareControler.read(devfd, buf, BUFSIZE);
                        if (retSize > 0) {
                            String str = null;
                            try {
                                str = new String(buf, 0, retSize,"GBK");
                                remoteData.append(str);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            if (fromTextView.getLineCount() > MAXLINES) {
                                int nLineCount = fromTextView.getLineCount();
                                int i = 0;
                                for (i = 0; i < remoteData.length(); i++) {
                                    if (remoteData.charAt(i) == '\n') {
                                        nLineCount--;

                                        if (nLineCount <= MAXLINES) {
                                            break;
                                        }
                                    }
                                }
                                remoteData.delete(0, i);
                                fromTextView.setText(remoteData.toString());
                                Log.d("TAG", "======" + i + ")");
                            } else {
                                fromTextView.append(str);
                            }

                           // ((ScrollView)findViewById(R.id.scroolView)).fullScroll(View.FOCUS_DOWN);
                        }
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };


    private TimerTask task = new TimerTask() {
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };

    public void onClick(View v)
    {
        switch (v.getId()) {
            case R.id.sendButton:
                String str = toEditor.getText().toString();
                try {

                    if (str.length() > 0) {
                        if (str.charAt(str.length()-1) != '\n') {
                            str = str + "\n";
                        }
                        byte[] gbkbytes =str.getBytes("GB2312");
                        int ret = HardwareControler.write(devfd, gbkbytes);
                        if (ret > 0) {

                            str = ">>> " + str;
                            if (remoteData.length() > 0) {
                                if (remoteData.charAt(remoteData.length()-1) != '\n') {
                                    remoteData.append('\n');
                                    fromTextView.append("\n");
                                }
                            }
                            remoteData.append(str);
                            fromTextView.append(str);

                            //((ScrollView)findViewById(R.id.scroolView)).fullScroll(View.FOCUS_DOWN);
                        } else {
                            Toast.makeText(this,"Fail to send!",Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId())
        {
            case R.id.speed:
            {
                speed=speed_val[position];
            }
            break;
            case R.id.dataBits:
            {
                dataBits=dataBits_val[position];
            }
            break;
            case R.id.stopBits:
            {
                stopBits=stopBits_val[position];
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        HardwareControler.close(devfd);
        switch (group.getCheckedRadioButtonId())
        {
            case R.id.serial_1:
                devName="dev/ttyAMA2";
                break;
            case R.id.serial_2:
                devName="dev/ttyAMA3";
                break;
        }
        devfd = HardwareControler.openSerialPort( devName, speed, dataBits, stopBits );
    }
}
